﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;

    //表格管理器.
public static class ExcelTableRender 
    {
        static Dictionary<string, EC_Table> mExcelTables;
        public static string TablePath = "Table/Excel/"; 
     static  public Dictionary<string, EC_Table> ExcelTables
     {
            get
            {
                if (mExcelTables == null) mExcelTables = new Dictionary<string, EC_Table>();
                return mExcelTables;
            }
            set { mExcelTables = value; }
     }

    public static void SetTablePath(string path)
    {
        TablePath = path;
    }  
    public static T GetValue<T>(string tableName,int rowID,int level,string elemName)
    {
        return GetTable(tableName).GetRow(rowID, level).Value<T>(elemName);
    }
      static public EC_Table GetTable(string tbName)  
      {
           string FullPath = TablePath + tbName;
           string AllStrs =""; 
         //  NGUIDebug.Log(FullPath);
          //已经加载过从缓存直接返回.
          if (ExcelTables.ContainsKey(tbName))
          {
              return ExcelTables[tbName];
          }
          //文件不存在返回.
          if (File.Exists(FullPath)) 
          {
              StreamReader r = File.OpenText(FullPath);
              AllStrs = r.ReadToEnd(); 
            
          }
          else
          {
              TextAsset testAsset = Resources.Load(FullPath, typeof(TextAsset)) as TextAsset;
              AllStrs = testAsset.text;
          }
       
          EC_Table newTable = new EC_Table();
          ExcelTables.Add(tbName, newTable);

          string lastKey="";
          string[] lastValue =  null;
          string[] allRows = AllStrs.Split('\n');
          string[] typeList= null;
          string[] nameList =null;

          for (int i = 0; i < allRows.Length;i++)
          {
              //ReadNames
              if (i == 0) 
              {
                  string strNames = allRows[i];
                  strNames = strNames.TrimEnd('\r'); 
                  nameList = strNames.Split('\t');
                  continue;
              }
              //ReadTypes
              if (i == 1) 
              {
                  string strTypes;
                  strTypes = allRows[i];
                  strTypes = strTypes.TrimEnd('\r');
                  typeList = strTypes.Split('\t');
                  lastValue  = new string[typeList.Length];
                  continue;
              }

              //跳过前三行 空行 第一个字符为'#'的行
              if (i < 3 || allRows[i].Length < 1 || allRows[i][0] == '#') 
              {
                  continue;
              }
              string strValues=allRows[i];
            
              strValues = allRows[i].TrimEnd('\r');
              
              string[] strCol = mySplit(strValues,typeList,'\t');
              if (strCol.Length == 0) 
              {
                  continue;
              }
              string sKey=strCol[0];
              string[] valuesList= new string[strCol.Length];
              if (sKey == "" || sKey == "--")
              {
                  sKey = lastKey;
                  valuesList[0] = sKey;
                  for (int j = 0; j < strCol.Length; j++)
                  {
                      if (strCol[j] == "" || strCol[j] == "--")
                      {
                          valuesList[j] = lastValue[j];
                      }
                      else
                      {
                          valuesList[j] = strCol[j];
                          lastValue[j] = strCol[j];
                      }
                  }
              }
              else
              {
                  lastKey = sKey;
                  for (int k = 0; k < strCol.Length;k++ )
                  {
                      if (strCol[k] == "--")
                      {
                          valuesList[k] = "0";
                          lastValue[k] = "0";
                      }
                      else 
                      {
                         valuesList[k] = strCol[k];
                         lastValue[k] =strCol[k];
                      }
                  }
              }
              newTable.AddRowData(valuesList,typeList,nameList,sKey);
          }

           return newTable;
        }

      static string[] mySplit(string Str,string[] typeList,char regix)
      {
          string[] StrCols = Str.Split(regix);
          for (int i = 0; i < StrCols.Length; i++) 
          {
              if (StrCols[i] == "" && typeList[i].ToLower() != "string") 
              {
                  StrCols[i] = "--";
              }
          }
          return StrCols;
      }
       
    } 
    //表.
    public class EC_Table 
    {
        Dictionary<string, List<EC_Row>> mTableRows;
        public Dictionary<string, List<EC_Row>> TableRows 
        {
            get 
            {
                if (mTableRows == null) mTableRows = new Dictionary<string, List<EC_Row>>();
                return mTableRows;
            }
            set { mTableRows = value; }
        }
        public void AddRowData(string[] valueList,string[] typeList,string[] nameList,string key)
        {
           EC_Row newRow = new EC_Row();
           for (int i = 0; i < typeList.Length;i++)
           {
               EC_Elem elem = new EC_Elem();
               string tType = typeList[i].Trim();
               string StrType = tType.ToLower();
               switch(StrType)
               {
                   case "string":
                       elem.Data = valueList[i];
                   break;
                   case "int":
                     elem.Data = int.Parse(valueList[i]);
                   break;
                   case "float":
                     elem.Data = float.Parse(valueList[i]);
                   break;
                   case "bool":
                   if (valueList[i] == "0" || valueList[i] == "1" || valueList[i] == "-1")
                   {
                       elem.Data = valueList[i] == "0" ? true : false;
                   }
                   else 
                   {
                       elem.Data = bool.Parse(valueList[i]);
                   }
                   break;
               }
               if (!newRow.Elems.ContainsKey(nameList[i]))
               {
                   newRow.Elems.Add(nameList[i], elem);
               }
           }
           if (!TableRows.ContainsKey(key)) 
           {
               TableRows[key] = new List<EC_Row>();
           }
           TableRows[key].Add(newRow);
        }

        public EC_Row GetRow(int rowID,int level)
        {
          return TableRows[rowID.ToString()][level];
        }
        public EC_Row GetRow(string rowID,int level)
        {
            return TableRows[rowID][level];
        }
    } 

    //行
    public  class EC_Row
    {
       Dictionary<string, EC_Elem> mElems;
       public Dictionary<string, EC_Elem> Elems
       { 
           get 
           {
               if (mElems == null) mElems = new Dictionary<string, EC_Elem>();
               return mElems;
           }

           set { mElems = value; }
       }
       public T Value<T>(string elemName)
       {
           return (T)Elems[elemName].Data;
       }
    }

    //元素
    public class EC_Elem 
    {
        public object Data;

       
    }

